
from flask import Blueprint, request, jsonify, g

from db_utils.postgresql_connection import PostgreSQLConnection
from db_utils.repositories.device_notify_table import DeviceNotifyTable
from push_device_task import PushDeviceTask

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

device_notify_blueprint = Blueprint('device_notify_blueprint', __name__)

@device_notify_blueprint.route('/create_notify', methods=['POST'])
def create_notify():
    
    title = request.form.get('title')
    content = request.form.get('content')
    type = request.form.get('type')
    device_id = request.form.get('device_id')

    if not title or not content or not type or not device_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            device_notify_table = DeviceNotifyTable(conn, cursor)
            status, result = device_notify_table.create_notify(title, content, type, device_id)

        except Exception as e:
            logger.error("Error creating notify: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if not status:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})
            else:

                # 推送通知消息到设备
                push_device_task = PushDeviceTask()

                push_device_task.send_notification_message_to_redis_by_device_id(device_id, title, content)

                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"id": result}})

@device_notify_blueprint.route('/get_notify_by_device_id', methods=['GET'])
def get_notify_by_device_id():
    
    device_id = request.args.get('device_id')
    limit = request.args.get('limit', default=5, type=int)
    offset = request.args.get('offset', default=0, type=int)

    if not device_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            device_notify_table = DeviceNotifyTable(conn, cursor)
            status, notify = device_notify_table.get_notify(device_id, limit, offset)
            _, count = device_notify_table.count_notify(device_id)

        except Exception as e:
            logger.error("Error getting notify by device id: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": notify, "count": count}})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": notify, "resultBody": None})

@device_notify_blueprint.route('/get_all_notify', methods=['GET'])
def get_all_notify():
    
    title = request.args.get('title', default=None)
    content = request.args.get('content', default=None)
    type = request.args.get('type', default=None)
    device_id = request.args.get('device_id', default=None)
    limit = request.args.get('limit', default=10, type=int)
    offset = request.args.get('offset', default=0, type=int)

    with PostgreSQLConnection() as (conn, cursor):
        try:
            device_notify_table = DeviceNotifyTable(conn, cursor)
            status, notify = device_notify_table.get_all_notify(title, content, type, device_id, limit, offset)
            _, count = device_notify_table.count_all_notify(title, content, type, device_id)

        except Exception as e:
            logger.error("Error getting all notify: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": notify, "count": count}})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": notify, "resultBody": None})
            


@device_notify_blueprint.route('/delete_notify', methods=['POST'])
def delete_notify():
    
    notify_ids = request.form.getlist('notify_ids[]')

    if not notify_ids:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            device_notify_table = DeviceNotifyTable(conn, cursor)
            status, result = device_notify_table.delete_notify(notify_ids)

        except Exception as e:
            logger.error("Error deleting notify: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": None})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})




